#pragma once

#include<iostream>
#include<string>
#include<pthread.h>
#include<unistd.h>
#include<functional>
#include<sys/syscall.h>

#define get_lwp_id() syscall(SYS_gettid)

using func_t =std::function<void()>;
const std::string threadname="None-Name";

class Thread
{
public:
    Thread(func_t func,const std::string &name=threadname)
        :_name(name)
        ,_func(func)
    {
        std::cout << "create thread obj success" << std::endl;
    }

    static void* routine(void* args)
    {
        Thread*self=static_cast<Thread*>(args);
        self->_isrunning=true;
        self->_func();
        self->_lwp=get_lwp_id();
        pthread_exit((void*)0);
    }

    void start()
    {
        int n=pthread_create(&_tid,nullptr,routine,this);
        if(n==0)
            std::cout << "run thread success" << std::endl;
    }

    void join()
    {
        if (!_isrunning)
            return;

        int n = pthread_join(_tid, nullptr);
        if (n == 0)
        {
            std::cout << "pthread_join success" << std::endl;
        }
    }

    ~Thread()
    {}
private:
    std::string _name;
    func_t _func;
    pthread_t _tid;
    bool _isrunning;
    pid_t _lwp;
};

